package com.itheima04.aop;

import com.itheima.case2.dao.UserDao;
import com.itheima.case2.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyUtil {
    public static UserDao userDao;
//    public static SqlSession sqlSession ;

    //获取代理类对象(动态代理)
    public static UserService3 getProxy(){

        //被代理类对象
        UserSerivceImpl3 usi3 = new UserSerivceImpl3();

        //代理类对象: 是对被代理类的增强
        ClassLoader loader = usi3.getClass().getClassLoader();
        Class<?>[] interfaces = usi3.getClass().getInterfaces();
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //固定: 不允许事务自动提交
                SqlSession sqlSession = SqlSessionUtil.getSession(false);
                userDao = sqlSession.getMapper(UserDao.class);
//                System.out.println("ud:" + userDao);

                Object obj;
                try {
                    //不固定!!! 切入点
                    String name = method.getName();
                    obj = method.invoke(usi3, args);
                    //等价于上面这一行
//                    usi3.deleteUser((Integer)args[0]);
                    //固定: 提交事务
                    SqlSessionUtil.commitAndClose(sqlSession);
                } catch (RuntimeException e) {
                    //固定: 回滚事务
                    SqlSessionUtil.rollbackAndClose(sqlSession);
                    throw new RuntimeException(e.getMessage());
                }

                return obj;
            }
        };

        UserService3 proxy = (UserService3) Proxy.newProxyInstance(loader, interfaces, h);
        return proxy;
    }
}
